package com.simba.server.components;

import com.simba.GlobalParam;
import com.simba.common.log.LogUtil;
import com.simba.server.ServerManager;
import com.simba.server.components.data.SorterInfo;
import org.apache.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;

import java.io.File;
import java.util.concurrent.ConcurrentHashMap;

public class SorterManager
{
	private static class PlcManagerHolder
	{
		private static final SorterManager INSTANCE = new SorterManager();
	}

	private static final Logger logger = Logger.getLogger(SorterManager.class);


	private final ConcurrentHashMap<String, SorterInfo> wheelSorters = new ConcurrentHashMap<>();

	private String configFile;
	private String configFilePath;

	public String getConfigFile()
	{
		return configFile;
	}

	public void setConfigFile(String configFile)
	{
		this.configFile = configFile;
	}

	public String getConfigFilePath()
	{
		return configFilePath;
	}

	public void setConfigFilePath(String configFilePath)
	{
		this.configFilePath = configFilePath;
	}

	public static SorterManager getInstance()
	{
		return PlcManagerHolder.INSTANCE;
	}

	private SorterManager()
	{

	}

	public void init(String _configFile)
	{
		this.setConfigFile(_configFile);
		this.setConfigFilePath("etc" + GlobalParam.PATH_SEP + this.configFile);

		Document rootDoc;
		try
		{
			rootDoc = ServerManager.getInstance().getXmlDocFromFile(this.configFilePath);

			Element root = rootDoc.getRootElement();
			Element rootElement = root.getChild("Wheel-Sorters");
			java.util.List<Element> client = rootElement.getChildren();

			for (Element element : client)
			{
				String id = element.getAttributeValue("id");
				String name = element.getAttributeValue("name");
				String packet = element.getAttributeValue("is-packet");

				SorterInfo info = new SorterInfo();
				info.setSorterId(id);
				info.setSorterName(name);
				info.setPacket(Boolean.parseBoolean(packet));
				info.setSorterStatus("0"); // init 0

				this.wheelSorters.put(id, info);
			}

		}
		catch (Exception ex)
		{
			LogUtil.LogError(logger, "Init PLC Clients Manager Error -- Exception : " + ex);
		}
	}

	public SorterInfo getWheelSorterByID(String sorterID)
	{
		return this.wheelSorters.get(sorterID);
	}


}
